/*
 *   Copyright 2012-present OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

// Packages
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import {
  Button,
  Classes,
  Dialog,
  FormGroup,
  InputGroup,
  Intent,
  Position
} from '@blueprintjs/core';
import { FormValidation } from 'calidation';

// Services
import { LicenseService } from '../../../../../services';

// Utils
import { Saiku } from '../../../../../utils';

class AddLicenseUserDialog extends Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: false
    };

    this.formValidationConfig = {
      username: {
        isRequired: 'Username field is required'
      }
    };
  }

  handleSubmit = ({ fields, errors, isValid }) => {
    if (isValid) {
      const { getLicenseUsers, onClose } = this.props;
      const { username } = fields;

      this.setState({ loading: true });

      LicenseService.postLicenseUser(username)
        .then(res => {
          this.setState({ loading: false });

          if (res.status === 200) {
            Saiku.toasts(Position.TOP_RIGHT).show({
              icon: 'tick',
              intent: Intent.SUCCESS,
              message: 'User added'
            });

            getLicenseUsers();
            onClose();
          } else {
            Saiku.toasts(Position.TOP_RIGHT).show({
              icon: 'error',
              intent: Intent.DANGER,
              message: res.statusText
            });
          }
        })
        .catch(error => {
          Saiku.toasts(Position.TOP_RIGHT).show({
            icon: 'error',
            intent: Intent.DANGER,
            message: 'Something went wrong'
          });
        });
    }
  };

  renderForm() {
    const { onClose } = this.props;
    const { loading } = this.state;

    return (
      <FormValidation
        onSubmit={this.handleSubmit}
        config={this.formValidationConfig}
        style={{ margin: 0 }}
      >
        {({ fields, errors, submitted }) => (
          <Fragment>
            <div className={Classes.DIALOG_BODY}>
              <FormGroup
                label="Username"
                labelFor="username"
                intent={
                  submitted && errors.username ? Intent.DANGER : Intent.NONE
                }
                helperText={submitted && errors.username ? errors.username : ''}
              >
                <InputGroup
                  name="username"
                  intent={
                    submitted && errors.username ? Intent.DANGER : Intent.NONE
                  }
                  autoFocus
                />
              </FormGroup>
            </div>
            <div className={Classes.DIALOG_FOOTER}>
              <div className={Classes.DIALOG_FOOTER_ACTIONS}>
                <Button
                  type="submit"
                  text="Add"
                  intent={Intent.DANGER}
                  loading={loading}
                />
                <Button text="Close" onClick={onClose} />
              </div>
            </div>
          </Fragment>
        )}
      </FormValidation>
    );
  }

  render() {
    const { onClose } = this.props;

    return (
      <Dialog
        title="Add User"
        icon="plus"
        canOutsideClickClose={false}
        isOpen={true}
        onClose={onClose}
      >
        {this.renderForm()}
      </Dialog>
    );
  }
}

AddLicenseUserDialog.propTypes = {
  getLicenseUsers: PropTypes.func.isRequired,
  onClose: PropTypes.func.isRequired
};

export default AddLicenseUserDialog;
